﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Data.Entity;
using XRERP.Models;
using XRERP.utils;

namespace XRERP.Controllers
{
    /// <summary>
    /// 请款单系统
    /// </summary>
    public class INVOICEController : Controller
    {

        private MySqlDB db = new MySqlDB();

        // GET: INVOICE
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 获取请款单信息
        /// </summary>
        /// <param name="uuid"></param>
        /// <param name="numbr"></param>
        /// <returns></returns>
 /*       public ActionResult getInvoiceInfo(String uuid="",String numbr="")
        {

            var data = from a in db.xr_bl_probillmain select new
            {
                pro_time=a.pro_time.ToString(),
                a.probill_number,
                a.proarc_uuid,
                a.proarc_number
            };

            if (!uuid.Equals(""))
            {
                data = data.
                    Where(x => x.proarc_uuid.Contains(uuid));
            }

            if (!numbr.Equals(""))
            {
                data = data.
                    Where(x => x.proarc_number.Contains(numbr));
            }


            if (null != data)
               {
                return Json(new
                {
                    code = 200,
                    data = data.First()
                });
                }
            else
                return Json(new
                {
                    code = 300
                });
        }
        */

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="uuid">项目档案编号</param>
        /// <returns></returns>
        public ActionResult getInvoiceInfos(String uuid)
        {
            var data = from a in db.xr_bl_probillmain
                       from b in db.xr_bl_probill
                       where
                            a.probillmain_uuid== b.probillmain_uuid
                            &&a.proarc_uuid == uuid
                            && a.probill_flag == "1"
                       select new
                       {
                           b.clientinfo_uuid,
                           b.device_number,
                           b.device_price,
                           lease_begindate=b.lease_begindate.ToString(),
                           b.lease_days,
                           lease_enddate=b.lease_enddate.ToString(),
                           b.lease_total,
                           a.proarc_number,
                           a.proarc_uuid
                      };

            return Json(data);
        }

        /// <summary>
        /// 添加请款单
        /// </summary>
        /// <param name="probill"></param>
        /// <returns></returns>
        public ActionResult AddProjectFile(xr_bl_probill probill)
        {

            JRow<xr_bl_probill> json = new JRow<xr_bl_probill>();

            try
            {
                probill.probill_uuid = Tools.getGuid();
                //probill.probill_flag = "1";

                db.xr_bl_probill.Add(probill);
                if (db.SaveChanges() == 1)
                {
                    json.isError = false;
                    json.code = 200;
                    json.msg = "保存成功!";
                    json.RowData = probill;
                }
                else
                {
                    json.isError = true;
                    json.code = 300;
                    json.msg = "保存失败，请重试或与管理员联系！";
                }
            }
            catch (Exception e)
            {
                json.code = 505;
                json.isError = true;
                json.msg = e.ToString();
            }


            return Json(json);
        }

        /// <summary>
        /// 添加请款单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddInvoice(xr_bl_probillmain probillmain,xr_bl_probill[] rows)
        {
            DateTime date = DateTime.Now;
            String year = date.Year.ToString();
            JR json = new JR();

            var transaction=db.Database.BeginTransaction();

            try
            {

                var data = db.xr_dl_numbermng.
                    Where(x => x.number_year == year).
                    Where(x => x.number_type == "4");
                var number = data.Count() == 0 ? null : data.First().mng_number;
                var firstdata = data.Count() == 0 ? new xr_dl_numbermng() : data.First();
                if (null == number || number.Equals(""))
                {
                    probillmain.probill_number = "Q" + year + "00000001";
                    number = "1";
                }
                else
                {
                    int tmpnum = Convert.ToInt32(number) + 1;
                    number = tmpnum.ToString();
                    probillmain.probill_number = "Q" + year + Tools.getNumber(number);
                }

                firstdata.mng_number = number;
                if (data.Count() == 0)
                {
                    firstdata.number_uuid = Tools.getGuid();
                    firstdata.number_year = year;
                    firstdata.number_type = "4";
                    db.xr_dl_numbermng.Add(firstdata);
                }
                else
                {
                    db.Entry(firstdata).State = EntityState.Modified;
                    
                }


                probillmain.probillmain_uuid = Tools.getGuid();
                probillmain.probill_flag = "1";
                probillmain.validflag = "1";

                decimal tmp=0;
                
                for(int i=0;i< rows.Length;i++)
                {

                    rows[i].probillmain_uuid = probillmain.probillmain_uuid;
                    rows[i].probill_uuid = Tools.getGuid();
                    rows[i].validflag = "1";
                    rows[i].settlement_total = 0;

                    tmp += (decimal)rows[i].lease_total;

                    //添加明细
                    Addprobilldetail(rows[i]);

                    db.xr_bl_probill.Add(rows[i]);
                }

                probillmain.settlement_total = tmp;

                //请款单主表
                db.xr_bl_probillmain.Add(probillmain);
                //db.Configuration.ValidateOnSaveEnabled = false;
                if (db.SaveChanges()>1)
                {
                    json.code = 200;
                    json.msg = "请款单添加成功！请款单编号："+ probillmain.probill_number;
                    json.message = probillmain.probill_number;
                }
                else
                {
                    json.code = 300;
                    json.msg = "请款单添加失败！请重试！";
                    json.message = "-1";
                }

                transaction.Commit();
            }
            catch(Exception e)
            {
                json.code = 300;
                json.msg = "请款单添加失败!错误原因"+e.Message.ToString();
                json.message = "-1";
                transaction.Rollback();
            }
            return Json(json);
        }

        /// <summary>
        /// 分月计算明细信息
        /// </summary>
        /// <param name="probill"></param>
        /// <returns></returns>
        public bool Addprobilldetail(xr_bl_probill probill) 
        {


            try { 

            DateTime start = (DateTime) probill.lease_begindate;
            DateTime end = (DateTime)probill.lease_enddate;

            
                //如果为同月则直接添加不进行计算
                if (start.ToString("yyyy-MM").Equals(end.ToString("yyyy-MM")))
                {
                    xr_bl_probilldetail probilldetail = new xr_bl_probilldetail();
                    probilldetail.probill_uuid = probill.probill_uuid;
                    probilldetail.probilldetail_uuid = Tools.getGuid();
                    probilldetail.lease_date = start.ToString("yyyyMM");//所属月份

                    probilldetail.leasedate_days = probill.lease_days;
                    probilldetail.leasedate_total = probill.lease_total;
                    probilldetail.settlement_flag = "0";

                    db.xr_bl_probilldetail.Add(probilldetail);

                }
                else
                {
                    int year = end.Year - start.Year;
                    int month = year * 12 + end.Month - start.Month + 1;

                    for (int i = 1; i <= month; i++)
                    {
                        xr_bl_probilldetail probilldetail = new xr_bl_probilldetail();
                        probilldetail.probill_uuid = probill.probill_uuid;
                        probilldetail.probilldetail_uuid = Tools.getGuid();
                        probilldetail.lease_date = start.ToString("yyyyMM");//所属月份
                        probilldetail.settlement_flag = "0";
                        if (i != month)
                        {

                            int day = DateTime.DaysInMonth(start.Year, start.Month) - start.Day + 1;
                            probilldetail.leasedate_days = day;
                            probilldetail.leasedate_total = day * probill.device_price * probill.device_number;
                            if (i == 1)
                            {
                                start = DateTime.Parse(start.ToString("yyyy-MM") + "-01");
                            }
                            start = start.AddMonths(1);
                        }
                        else
                        {
                            int day = end.Day;
                            probilldetail.leasedate_days = day;
                            probilldetail.leasedate_total = day * probill.device_price * probill.device_number;

                        }
                        db.xr_bl_probilldetail.Add(probilldetail);

                    }
                }
                /*
                if(db.SaveChanges()<1)
                {
                    throw new Exception("分月明细数据保存失败!");
                }*/
            }catch(Exception e)
            {
                throw e;
            }

            return true;
        }
    }
}